import re
import requests
import support


def get_reply(url, filter_time):
    response = requests.get(url)
    html_content = response.text
    pattern = r'"oid=(\d+)"'
    match = re.search(r'oid=(\d+)', html_content)
    # 如果找到了匹配的文本，则使用 group 函数来提取 oid 数据
    if match:
        oid = match.group(1)
        print(f'oid = {oid}')
        res = requests.get(f"https://api.bilibili.com/x/v2/reply/main?oid={oid}&type=1")
        data = res.json()['data']
        top = data['top']['upper']
        top_reply_id = top['rpid']
        total = data['top_replies'][0]['rcount']
        filter_mid = data['top_replies'][0]['member']['mid']

        # 查询所有页的评论
        replies = []
        p = 1
        while total > len(replies):
            res = requests.get(
                f'https://api.bilibili.com/x/v2/reply/reply?oid={oid}&pn={p}&ps=20&root={top_reply_id}&type=1')
            replies += res.json()['data']['replies']
            p += 1

        # 过滤评论人和超出截至时间的回复
        filter_replies_itr = filter(lambda it: (it['member']['mid'] != filter_mid) and
                                               (int(it['ctime']) < filter_time + 86400), replies)
        # 设置结果集
        results = list(map(lambda it: {
            'mid': it['mid'],
            'uname': it['member']['uname'],
            'ctime': support.second_to_time(it['ctime']),
            'message': it['content']['message']
        }, filter_replies_itr))

        # 去重！
        return del_repeat(results, 'mid')

    else:
        return []


def del_repeat(data, key):
    new_data = []  # 用于存储去重后的list
    values = []  # 用于存储当前已有的值
    for d in data:
        if d[key] not in values:
            new_data.append(d)
            values.append(d[key])
    return new_data

